package com.sherlocky.fsg.uid.configure;

import com.sherlocky.fsg.uid.UidGenerator;
import com.sherlocky.fsg.uid.impl.CachedUidGenerator;
import com.sherlocky.fsg.uid.impl.DefaultUidGenerator;
import com.sherlocky.fsg.uid.worker.DisposableWorkerIdAssigner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

/**
 * 使用 @Configuration 自动装配 UidGenerator
 * @author: zhangcx
 * @date: 2019/5/10 15:37
 */
@Configuration
//@ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true)
public class UidGeneratorConfig {

    @Bean
    @ConditionalOnMissingBean
    public DisposableWorkerIdAssigner getDisposableWorkerIdAssigner() {
        return new DisposableWorkerIdAssigner();
    }

    @Lazy(value = false)
    @Bean
    @ConditionalOnProperty(name = "uid.generator.strategy", havingValue = "default", matchIfMissing = true)
    public UidGenerator getDefaultUidGenerator(DisposableWorkerIdAssigner assigner) {
        DefaultUidGenerator g =  new DefaultUidGenerator();
        g.setWorkerIdAssigner(assigner);
        /** Specified bits & epoch as your demand. No specified the default value will be used */
        g.setTimeBits(29);
        g.setWorkerBits(21);
        g.setSeqBits(13);
        g.setEpochStr("2016-09-20");
        System.out.println("########################################");
        System.out.println("### DefaultUidGenerator");
        System.out.println("****************************************");
        return g;
    }

    @Bean
    @ConditionalOnProperty(name = "uid.generator.strategy", havingValue = "cached", matchIfMissing = false)
    public UidGenerator getCachedUidGenerator(DisposableWorkerIdAssigner assigner) {
        CachedUidGenerator g =  new CachedUidGenerator();
        g.setWorkerIdAssigner(assigner);
        System.out.println("########################################");
        System.out.println("### CachedUidGenerator");
        System.out.println("****************************************");
        return g;
    }
}
